window.define(["backbone"], function () {
    var routesMap = {
        "":"layout.inithome",

        "campaign":"campaign.index",
        "campaign/detail(/:id)":"campaign.detail",
        "campaign/:id":"campaign.info",
        "campaign/:id/strategy(/:id)":"strategy.detail",
        "campaign/:id/creative(/:id)":"creative.detail",

        "customer":"customer.index",
        "customer/detail(/:id)":"customer.detail",

        "agent":"agent.index",

        "report":"report.index",
        "report/detail(/:id)":"report.detail",

        "tool/target":"targetPack.index",
        "tool/target/detail(/:id)":"targetPack.detail",

        "tool/crowd":"crowd.index",

        "finance":"finance.index",

        "user":"user.index",
        //":controller(/:view)(/:id)":"controller.view",
        "login":"account.login",
        "*error": "defaultError"
    };
    var Router = window.Backbone.Router.extend({
        routes: routesMap
    });
    var router = new Router();
    //彻底用on route接管路由的逻辑，这里route是路由对应的value
    router.on("route", function (key, params) {
        window.reqModalCommon.loadingStart();
        $.ExtNotify.destroy();
        var routeInfo=routerCommon.getRouterInfo(key, params);
        if(routerCommon.checkExistPath(routeInfo.controller,routeInfo.view)){
            switch(key){
                case "defaultError":
                    routerCommon._errorUrl();
                    break;
                case "account.login":
                    if(router.layoutIndexView){
                        routerCommon.stopListening(router.layoutIndexView);
                        router.layoutIndexView=null;
                    }
                    require(["css!../css/pageLogin.css"], function () {
                        require(window.backboneCommon.getViewByArr(["Layout.Login"]), function (View) {
                            var view = new View();
                            routerCommon.initRouterPage(routeInfo);
                        });
                    });
                    break;
                default:
                    routerCommon.initLayoutIndex(function(){
                        routerCommon.initRouterPage(routeInfo);
                    });
            }
        }
    });
    var routerCommon={
        getRouterInfo:function (key, params) {
            var paramLower=[];
            for(var pi=0;pi<params.length;pi++){
                paramLower.push(params[pi])
            }
            var router=key;
            var controller="";
            var view="";
            var arrParam=paramLower;
            if(key!=="defaultError"){
                switch(key){
                    case "controller.view":
                        controller=paramLower[0];
                        view=paramLower[1];
                        router=controller+"."+view;
                        arrParam=[];
                        break;
                    default:
                        var temp=key.split(".");
                        controller=temp[0];
                        view=temp[1];
                        router=key;
                        if(view==="view"){
                            view=paramLower[0];
                            router=controller+"."+view;
                            arrParam=[];
                        }
                }
            }
            return {router:router,controller:controller,view:view,param:arrParam}
        },
        checkExistPath:function (controller,view) {
            var b=false;
            if(controller.length>0 && view.length>0){
                b=window.backboneCommon.checkExistPath(controller,view);
                if(!b){this._errorUrl()}
            }else{
                this._errorUrl();
            }
            return b
        },
        _errorUrl:function(){
            window.location.href="#login";
        },
        initLayoutIndex:function(cb){
            var token=$.cookie('usertoken');
            if(token){
                var check=function () {
                    router.layoutIndexView.checkLogin(function () {cb()})
                };
                if(router.layoutIndexView){
                    check();
                }else{
                    require(window.backboneCommon.getViewByArr(["Layout.Index"]), function (View) {
                        var view = new View();
                        router.layoutIndexView = view.view;
                        check();
                    });
                }
            }else{
                this._errorUrl();
            }
        },
        initRouterPage:function(json){
            var self=this;
            var pageInfo=window.backboneCommon._getMvcInfo(json.router);
            window.backboneCommon.setTitleName(pageInfo.page.title);
            self._checkMenuPower(pageInfo.page.menuId,function(){
                require(window.backboneCommon.getControllerByArr(pageInfo.controller), function (Controller) {
                    var controller=new Controller();
                    require(window.backboneCommon.getViewByArr(pageInfo.view),function(View){
                        window.reqModalCommon.loadingEnd();
                        var view=new View(json.param,json);
                        if (router.currentView && router.currentView !== view.view) {
                            self.stopListening(router.currentView);
                            self._recursionStopAttach(router.currentView);
                        }
                        if(view["initView"]){view["initView"](json.param,json)}
                        router.currentView=view.view;
                        if(pageInfo.page.view.length>0){
                            if(controller[pageInfo.page.view]){
                                controller[pageInfo.page.view](json.param,json);
                            }
                        }
                    });
                });
            });
        },
        _checkMenuPower:function(menuId,cb){
            if(menuId){
                router.layoutIndexView.checkMenuPower(menuId,function(res){
                    if(res && cb){cb()}
                });
            }else{
                if(cb){cb()}
            }
        },
        _recursionStopAttach:function (view) {
            if(view["viewAttach"]){
                for(var v in view["viewAttach"]){
                    if (view["viewAttach"].hasOwnProperty(v)) {
                        this.stopListening(view["viewAttach"][v].view);
                        this._recursionStopAttach(view["viewAttach"][v].view)
                    }
                }
            }
        },
        stopListening:function (view){
            view.undelegateEvents();
            view.stopListening();
        }
    };
    return router;
});